def read_hidden_code_from_image(image_path):
    with open(image_path, 'rb') as f:
        content = f.read()

    # 查找可能的代码分隔符，例如"###CODE_START###"
    separator = b'###CODE_START###'
    if separator in content:
        code_part = content.split(separator)[1]
        return code_part.decode('utf-8')
    else:
        # 如果没有分隔符，尝试读取EOF后的所有内容
        # 首先找到正常的图片结束位置
        # 对于JPEG，FF D9是结束标记
        # 对于PNG，IEND标记表示结束
        if content.endswith(b'\xFF\xD9'):  # JPEG
            eof_pos = content.rfind(b'\xFF\xD9') + 2
        elif b'IEND' in content:  # PNG
            iend_pos = content.rfind(b'IEND')
            eof_pos = iend_pos + 8  # IEND标记后还有4字节CRC
        else:
            # 其他格式，尝试读取最后1KB内容
            eof_pos = max(0, len(content) - 1024)

        hidden_data = content[eof_pos:]
        return hidden_data.decode('utf-8', errors='ignore')


def write_code_to_image(image_path, code_text, output_path=None):
    if output_path is None:
        output_path = image_path

    with open(image_path, 'rb') as f:
        content = f.read()

    # 查找原始图片的EOF位置
    if content.endswith(b'\xFF\xD9'):  # JPEG
        eof_pos = content.rfind(b'\xFF\xD9') + 2
    elif b'IEND' in content:  # PNG
        iend_pos = content.rfind(b'IEND')
        eof_pos = iend_pos + 8
    else:
        eof_pos = len(content)

    # 保留原始图片内容，并在EOF后添加代码
    new_content = content[:eof_pos] + b'###CODE_START###' + code_text.encode('utf-8')

    with open(output_path, 'wb') as f:
        f.write(new_content)

    return output_path
